<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrappe">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="单据编号" class="form-item">
              <j-input placeholder="请输入单据编号" v-model="mostImportantParams.billNo"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="统计状态" class="form-item">
              <j-dict-select-tag
                v-model="mostImportantParams.statisticalStatus"
                dictCode="statistical_status"
                placeholder="请选择统计状态"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="生产周期" class="form-item">
              <a-range-picker
                format="YYYY-MM-DD"
                :placeholder="['周一', '周日']"
                v-model="workingHours"
                @change="
                  (dates, dateStrs) => {
                    mostImportantParams.fillInStartTime = dateStrs[0]
                    mostImportantParams.fillInEndTime = dateStrs[1]
                  }
                "
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="填报类型">
              <j-dict-select-tag
                v-model="mostImportantParams.fillInType"
                dictCode="fill_in_type"
                placeholder="请选择填报类型"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="inputThisWeekTaskTime" type="primary" icon="plus"> 填报本周工时 </a-button>
      <a-button @click="inputLastWeekTaskTime" type="primary" icon="plus"> 补填上周工时 </a-button>
      <a-popover title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <a-row>
              <template v-for="(item, index) in defColumns">
                <template v-if="item.key != 'rowIndex' && item.dataIndex != 'action'">
                  <a-col :span="12" :key="index">
                    <a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox>
                  </a-col>
                </template>
              </template>
            </a-row>
          </a-checkbox-group>
        </template>
        <a style="float: right">
          <a-icon type="setting" :style="iconStyle" />
        </a>
      </a-popover>
    </div>
    <a-table
      ref="table"
      size="middle"
      :scroll="{ x: scrollX }"
      :components="draggableComponent"
      bordered
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      class="j-table-force-nowrap"
      :customRow="customRow"
      @change="handleTableChange"
    >
      <template slot="billNo" slot-scope="text">
        <span style="color: #00aaf0">{{ text }}</span>
      </template>
      <span slot="action" slot-scope="text, record">
        <!-- 已统计，可以查看 -->
        <a-button type="link" @click="handleDetail(record)"> 查看 </a-button>
        <!-- 未统计，可以撤回 -->
        <a-divider type="vertical" v-if="record.statisticalStatus === 'no'" />
        <a-popconfirm v-if="record.statisticalStatus === 'no'" title="确定撤回吗？" @confirm="revokeData(record)">
          <a-button type="link">撤回</a-button>
        </a-popconfirm>
      </span>
    </a-table>
    <!-- 自定义的简易抽屉，展示form内容 -->
    <simpleDrawer
      :buttonDisable="buttonDisable"
      :title="simpleDrawerTitle"
      :showSaveBtn="showSaveBtn"
      :isShowCloseBtn="isShowCloseBtn"
      @clickSubmit="clickSubmit"
      ref="simpleDrawer"
    >
      <addWorkHoursForm
        @submitSuccess="submitSuccess"
        @canClickSubmit="canClickSubmit"
        ref="iptTaskTime"
        :contentTitle="propData.contentTitle"
        :list="propData.list"
        :urlSubmitData="propData.urlSubmitData"
        :urlGetFormData="propData.urlGetFormData"
        :urlGetHistoryTrack="propData.urlGetHistoryTrack"
        :pierceBillNo="propData.pierceBillNo"
        :status="propData.status"
        :userType="propData.userType"
        :formDataParams="propData.formDataParams"
      ></addWorkHoursForm>
    </simpleDrawer>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
// 根据权限来给一个布尔值，可用来控制是否禁用
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, deleteAction } from '@/api/manage'
import simpleDrawer from '@/components/simpleDrawer'
import addWorkHoursForm from './modules/addWorkHoursForm.vue'
import { mapGetters } from 'vuex'
import moment from 'moment'
export default {
  name: 'index',
  mixins: [DisabledAuthFilterMixin, JeecgListMixin],
  components: {
    simpleDrawer,
    addWorkHoursForm,
  },
  data() {
    return {
      type: '',
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      dictOptions: {},
      description: '工时填报列表',
      // 表头
      columns: [],
      // 列设置
      settingColumns: [],
      // 列定义
      defColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          ellipsis: true,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '单据编号',
          align: 'center',
          dataIndex: 'billNo',
          width: 400,
          ellipsis: true,
          scopedSlots: {
            customRender: 'billNo',
          },
        },
        {
          title: '填报类型',
          align: 'center',
          dataIndex: 'fillInType_dictText',
          width: 132,
          ellipsis: true,
        },
        {
          title: '填报时间',
          align: 'center',
          dataIndex: 'fillInTime',
          width: 300,
          ellipsis: true,
          customRender(text, record) {
            if (!text) {
              return ''
            } else {
              return moment(text).format('YYYY年MM月DD日HH:mm:ss')
            }
          },
        },
        {
          title: '生产周期',
          align: 'center',
          dataIndex: 'fillTime',
          width: 300,
          ellipsis: true,
          customRender(text, record) {
            if (!record.fillInStartTime) {
              return ''
            } else {
              return (
                moment(record.fillInStartTime).format('YYYY年MM月DD日') +
                '--' +
                moment(record.fillInEndTime).format('YYYY年MM月DD日')
              )
            }
          },
        },
        {
          title: '填报人',
          align: 'center',
          dataIndex: 'fillInUser_dictText',
          width: 132,
          ellipsis: true,
        },
        {
          title: '统计状态',
          align: 'center',
          dataIndex: 'statisticalStatus_dictText',
          width: 132,
          ellipsis: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 160,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action',
          },
        },
      ],
      url: {
        // 列表渲染
        list: '/api/erp/hours/workmain/erpWorkingHours/allList',
        // 用于判断是否可以填报，上周已经填了才能填本周，以及已填报则无需再次填报
        canFillIn: '/api/erp/hours/workmain/erpWorkingHours/canFillIn',
        // 撤回数据接口,现在改为删除
        // revokeData: '/api/erp/hours/workmain/erpWorkingHours/revoke',
        revokeData: '/api/erp/hours/workmain/erpWorkingHours/delete',
        // 获取生产人员类型，白名单，生产统筹人员
        getUserType: '/api/erp/hours/personneltype/erpProductionPersonnelType/getUserTypeByUserId',
      },
      // 不会被其他查询条件覆盖的查询参数
      mostImportantParams: {
        // 获取已填报数据
        fillInStatus: 'yes',
        fillInUserEmpId: this.userInfo().empId,
      },
      workingHours: [],
      propData: {
        status: '',
        contentTitle: '',
        list: '',
        urlSubmitData: '',
        urlGetFormData: '',
        userType: '',
        listParams: {},
      },
      showSaveBtn: true,
      isShowCloseBtn: true,
      simpleDrawerTitle: '',
      buttonDisable: false,
    }
  },
  created() {
    // const _user = this.userInfo()
      // 判断是否需要补填上周工时
    this.inputLastWeekTaskTime('force')
  },
  methods: {
    ...mapGetters(['userInfo']),
    // 自定义查询
    searchQuery() {
      this.onClearSelected()
      this.loadData()
    },
    // 重置按钮
    searchReset() {
      // 因为这边的属性是从缓存中取的，用this.$options会取不到
      ;(this.mostImportantParams = {
        fillInStatus: 'yes',
        fillInUserEmpId: this.userInfo().empId,
      }),
        (this.workingHours = [])
      this.loadData(1)
    },
    // 点击单据穿透,本页面暂时未用到
    clickBillNo(record) {
      // this.showIptTaskTime('pierce')
      const _data = {
        status: 'pierce',
        contentTitle: '已补填工时',
        list: '/api/erp/hours/workdetail/erpWorkingHoursDetailed/findHistoryWeekTask',
        urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryPageById',
        // 查看流程历史记录
        urlGetHistoryTrack: '/api/erp/hours/approval/erpWorkingHoursApprovalLog/allList',
        pierceBillNo: record.id,
      }
      this.showIptTaskTime(_data)
      // 隐藏掉modal的保存按钮
      this.showSaveBtn = false
      this.simpleDrawerTitle = '详情'
    },
    // 查看按钮
    handleDetail(record) {
      // 或许还需要修改,可能还需要传record的某些信息
      // 需要对照着子组件去设置子组件的status
      // 点击的数据是上周的
      let _data = {}
      if (record.fillInType === 'miss') {
        _data = {
          status: 'viewLastWeek',
          contentTitle: '上周补填工时',
          list: '/api/erp/hours/workdetail/erpWorkingHoursDetailed/findHistoryWeekTask',
          // 主表查询的参数
          formDataParams: { id: record.id },
          // urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryHistoryWorkingHours',
          urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryPageById',
        }
      } else {
        _data = {
          status: 'viewThisWeek',
          contentTitle: '本周填报工时',
          list: '/api/erp/hours/workdetail/erpWorkingHoursDetailed/findHistoryWeekTask',
          // 主表查询的参数
          formDataParams: { id: record.id },
          // urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryHistoryWorkingHours',
          urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryPageById',
        }
      }

      this.showIptTaskTime(_data)
      // 隐藏掉modal的保存按钮
      this.showSaveBtn = false
      this.simpleDrawerTitle = '查看'
      // this.showIptTaskTime('view')
    },
    // 撤回按钮
    revokeData(record) {
      let params = {
        id: record.id,
      }
      deleteAction(this.url.revokeData, params).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 填报本周工时
    async inputThisWeekTaskTime() {
      this.isShowCloseBtn = true
      // 添加人员身份判断，如果是白名单，不需要填报
      await this.judgeUserType()
      if (this.propData.userType === 'white') {
        this.$message.info('您无需填报工时')
        return
      }
      // thisWeek:本周是否已填，no:未填，yes:已有数据（已填写或者因为跑了定时，已经将下周要补填的数据变过来了），not：本周无任务
      // thisWeekFillIn:本周是否已统计，未统计则没有这个属性，已统计且未填写则为miss
      // 增加thisWeekFillIn这个的判断是因为如果本周未填，但是已经统计过了，此时需要给用户提示，让其等到下周再补填
      const { thisWeek, lastWeek, thisWeekFillIn } = await this.canFillIn()
      // 添加数据判断，如果本周已填报，则提示本周已填报
      // 本周已填报
      if (thisWeek === 'yes'&&!thisWeekFillIn) {
        this.$message.warning('本周工时已填报')
        return
      }
      // 添加数据判断，如果上周未填报，则提示先补填上周
      // 上周未填报
      if (lastWeek === 'no') {
        this.$message.warning('请先补填上周工时')
        return
      }
      // 如果没有任务，则提示没有任务
      if (thisWeek === 'not'&&!thisWeekFillIn) {
        this.$message.warning('无本周任务')
        return
      }
      // 本周未填报，上周已填报
      if (thisWeek === 'no' && lastWeek !== 'no' && !thisWeekFillIn) {
        const _data = {
          status: 'add',
          contentTitle: '本周已填报工时',
          list: '/api/erp/hours/workdetail/erpWorkingHoursDetailed/findThisWeekTask',
          urlSubmitData: '/api/erp/hours/workmain/erpWorkingHours/add',
          urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryWorkingHours',
        }
        this.showIptTaskTime(_data)
      }
      // 这里只需要一个miss，thisWeek不需要判断。
      // 如果本周未填写，但是已经统计,则
      if (thisWeekFillIn === 'miss') {
        this.$message.warning('本周已统计，请您于下周补填')
        return
      }
      // 本周撤回
      if (thisWeek === 'cancel') {
        const _data = {
          status: 'revokeAdd',
          contentTitle: '本周已填报工时',
          list: '/api/erp/hours/workdetail/erpWorkingHoursDetailed/findHistoryWeekTask',
          urlSubmitData: '/api/erp/hours/workmain/erpWorkingHours/edit',
          urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryHistoryWorkingHours',
        }
        this.showIptTaskTime(_data)
      }
    },
    // 补填上周工时
    async inputLastWeekTaskTime(type) {
      var _this = this
      await this.judgeUserType()
      if (this.propData.userType === 'white') {
        if (!type) {
          this.$message.info('您无需补填工时')
        }
        return
      }
      const { lastWeek, lastWeekFillIn } = await this.canFillIn()
      if (type && type == 'force') {
        if (lastWeek === 'no') {
          this.$warning({
            content: '请补填上周工时',
            okText: '确认',
            onOk() {
              _this.isShowCloseBtn = false
              // 上周未填报
              const _data = {
                status: 'fillLastWeek',
                contentTitle: '已补填工时',
                list: '/api/erp/hours/workdetail/erpWorkingHoursDetailed/findHistoryWeekTask',
                urlSubmitData: '/api/erp/hours/workmain/erpWorkingHours/edit',
                urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryHistoryWorkingHours',
              }
              _this.showIptTaskTime(_data)
            }
          });
        }
      } else {
        // 本周已填报
        // lastWeekFillIn用来做上周工时是否是补填的判断，如果是补填，则值为miss,如果不是补填，则没值
        if (lastWeek === 'yes' && !lastWeekFillIn) {
          this.$message.warning('上周工时已填报，无需补填')
          return
        }
        if (lastWeekFillIn === 'miss') {
          this.$message.warning('上周工时已补填，无需再次补填')
          return
        }
        // 如果没有任务，则提示没有任务
        if (lastWeek === 'not') {
          this.$message.warning('无补填任务')
          return
        }
        // 上周未填报
        if (lastWeek === 'no') {
          const _data = {
            status: 'fillLastWeek',
            contentTitle: '已补填工时',
            list: '/api/erp/hours/workdetail/erpWorkingHoursDetailed/findHistoryWeekTask',
            urlSubmitData: '/api/erp/hours/workmain/erpWorkingHours/edit',
            urlGetFormData: '/api/erp/hours/workmain/erpWorkingHours/queryHistoryWorkingHours',
          }
          this.showIptTaskTime(_data)
        }
      }
    },
    clickSubmit() {
      // 调用子组件提交方法
      // 防止重复提交，直到子组件成功提交后，再解除按钮禁用
      this.buttonDisable = true
      this.$refs.iptTaskTime.submitData()
    },
    showIptTaskTime({
      status,
      contentTitle,
      list,
      urlSubmitData,
      urlGetFormData,
      urlGetHistoryTrack,
      pierceBillNo,
      formDataParams,
    }) {
      // 不用prop的话，会有加载顺序的问题，没办法直接修改this.$refs.iptTaskTime.status
      // 设置自定义状态用来区分是何种情况打开的页面，
      // 需求区分的几种情况，1.因为接口不同，是填报本周还是填报撤回的本周，或补填上周
      //                   2.是编辑还是查看
      this.propData.status = status
      // 文字配置部分
      this.propData.contentTitle = contentTitle
      // 子表查询接口，即table列表的接口
      this.propData.list = list
      // 数据提交接口
      this.propData.urlSubmitData = urlSubmitData
      // 主表查询的接口，即form表单的接口
      this.propData.urlGetFormData = urlGetFormData
      // 流程历史记录的查询
      this.propData.urlGetHistoryTrack = urlGetHistoryTrack
      // 穿透时候主表的查询参数
      this.propData.pierceBillNo = pierceBillNo
      // 查询主表需要的参数，因为需要这条记录的id，所以需要从这里传给子组件
      this.propData.formDataParams = formDataParams
      //simple的状态初始化
      this.showSaveBtn = true
      this.simpleDrawerTitle = '新建'
      this.$refs.simpleDrawer.visible = true
    },
    // 内部成功提交
    submitSuccess() {
      this.$refs.simpleDrawer.visible = false
      this.loadData(1)
    },
    // 查询本周工时
    async canFillIn() {
      // let params = {thisWeek:'fill_in'}
      return getAction(this.url.canFillIn).then((res) => {
        if (res.success) {
          return res.result
        }
      })
    },
    // 判断人员身份
    async judgeUserType() {
      const _info = this.userInfo()
      let params = {
        userId: _info.username,
      }
      return getAction(this.url.getUserType, params).then((res) => {
        if (res.success) {
          this.propData.userType = res.result.type
        }
      })
    },
    // 解除按钮的禁用
    canClickSubmit() {
      this.buttonDisable = false
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
